package com.hotel.BL;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.EntityNotFoundException;

import data.LanguageMaster;
import data.General;

public class LanguageLogic extends AbstractBL{
	public LanguageLogic(HttpServletRequest req, HttpServletResponse resp){
		this.req = req;
		this.resp = resp;
	}
	public void DeleteLanguage(long hotelId,String id){
		GenericLogic gLogic = new GenericLogic(req,resp);
		General g = gLogic.GetGeneral(hotelId);
		List<LanguageMaster> usingLanguage = g.getUsingLanguage();
		String[] idArray = id.split(",");
		for(int i=0;i<usingLanguage.size();i++){
			for(int x=0;x<idArray.length;x++){
				if(idArray[x].equals(String.valueOf(usingLanguage.get(i).getId()))){
					usingLanguage.remove(i);
					i--;
					break;
				}
			}
		}
		String nowLanguage = "";
		for(int i=0;i<usingLanguage.size();i++){
			nowLanguage += usingLanguage.get(i).getId() + ",";
		}
		nowLanguage = nowLanguage.substring(0, nowLanguage.length()-1);
		
		g.setUsingLanguageString(nowLanguage);
		
		try {
			gLogic.UpdateGenerlic(g);
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public List<LanguageMaster> GetAllLanguage4AdminLimit(long hotelId,long offset,long line){
		List<LanguageMaster> cList = new GenericLogic(req,resp).GetGeneral(hotelId).getUsingLanguage();
		if(cList.size() <= line){
			return cList;
		}else{
			if(cList.size() <= offset+line){
				int startIndex = (int)offset; 
				int lastIndex = cList.size()-1;
				return GetLanguageFromList(cList,startIndex,lastIndex);
			}else{
				int startIndex = (int)offset; 
				int lastIndex = (int) (offset+line);
				return GetLanguageFromList(cList,startIndex,lastIndex);
			}
		}
	}
	
	public List<LanguageMaster> GetLanguageFromList(List<LanguageMaster> cList,
			int startIndex,int lastIndex){
		List<LanguageMaster> result = new ArrayList<LanguageMaster>();
		for(int i= startIndex; i < lastIndex;i++){
			result.add(cList.get(i));
		}
		return result;
	}
	
	public List<LanguageMaster> GetLanguageRemain(List<LanguageMaster> usingLanguage){
		List<LanguageMaster> allLanguage = new MasterCreator().GetAllLanguageMaster();
		for(int i=0;i<allLanguage.size();i++){
			for(int x=0;x<usingLanguage.size();x++){
				if(allLanguage.get(i).getId() == usingLanguage.get(x).getId()){
					allLanguage.remove(i);
					i--;
					break;
				}
			}
		}
		return allLanguage;
	}
}
